<?php
/**
 * @file Cache.class.php
 * @package DsCache
 * @subpackage 
 * @version $id: 1.1, utf8, Sat Dec  5 14:10:38 CST 2009
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2009 MiFunny China Inc.
 * @url http://mifunny.info/
 * @desc 
 *   封装 DsCache, 单件模式 更易操作;
 * 使用:
 *   require_once 'Cache.class.php';
 *   define('DSCACHE_DIR','/tmp'); //缓存目录,必须指定
 *   define('DSCACHE_ENCODING', true); //默认 true, 使用 md5 加密文件名
 *   define('DSCACHE_LIFE_TIME', 900); //默认 900秒 
 *   
 *   Cache::set('select * from test', $data); //缓存变量
 *   Cache::get('cache id 1234'); //得到缓存
 *   Cache::remove('my cache file'); //清除特定缓存文件
 *   Cache::removeAll(); //清空缓存目录
 *
 * @ChangeLog
 * $id: 1.1, Sat Dec  5 14:31:41 CST 2009
 *   
 */
require_once 'DsCache.class.php';
class Cache{
    private static $instance = NULL;
    public $cache;

    /**
     * 构造,析构函数
     */
    private function __construct(){}
    public function _destruct(){
        if( self::$instance->cache ){
            unset( self::$instance->cache );
            unset( self::$instance );
        }
    }

    /**
     * 获得缓存静态对像
     */
    public static function getInstance(){
        if( is_null(self::$instance) ){
            self::$instance = new Cache();
            
            $cache_dir = defined('DSCACHE_DIR') ? DSCACHE_DIR : '/tmp';
            $life_time = defined('DSCACHE_LIFE_TIME') ? DSCACHE_LIFE_TIME : 900;
            $encoding_filename = defined('DSCACHE_ENCODING') ? DSCACHE_ENCODING : true;
            self::$instance->cache = new DsCache( 
                array( 'cache_dir' => $cache_dir,
                       'life_time' => $life_time,
                       'encoding_filename' => $encoding_filename,)
                );
        }
        return self::$instance;
    }

    public static function set($id, $data, $life_time=null, $sub_dir=null){
        return self::getInstance()->cache
            ->set($id, $data, self::_policy($life_time, $sub_dir) );
    } 

    public static function get($id, $life_time=null, $sub_dir=null){
        return self::getInstance()->cache
            ->get($id, self::_policy($life_time, $sub_dir) );
    }

    public static function remove($id){
        return self::getInstance()->cache->remove($id);
    }

    public static function removeAll(){
        return self::getInstance()->cache->removeAll();
    }
    
    private function _policy($life_time=null, $sub_dir=null){
        if( !is_null($life_time) ){
            $policy['life_time'] = $life_time;
            if( !is_null($sub_dir) )
                $policy['cache_subdir'] = $sub_dir;
        }else 
           $policy = null;
        return $policy;
    }

}//END class Cache
?>
